package com.tanhua.sso.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.sso.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 手机号登录
     *
     * @param phone //手机号
     * @param code  //验证码
     * @return
     */
    @Override
    public String login(String phone, String code) {

        String redisKey = "CHECK_CODE_" + phone;

        boolean isNew = false;

        //校验验证码
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.equals(code,redisData)){
            return null;    //验证码错误
        }

        //验证成功,删除验证码
        redisTemplate.delete(redisKey);

        //验证手机用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",phone);

        User user = this.userMapper.selectOne(queryWrapper);

        if (null == user){
            //需要注册该用户
            user = new User();
            user.setMobile(phone);
            //密码加密
            user.setPassword(DigestUtils.md5Hex("123456"));

            //user.setId(666L);

            //注册新用户
            this.userMapper.insert(user);
            isNew = true;

            //将该用户信息注册到环信平台
            Boolean result = this.huanXinApi.register(user.getId());
            if (!result){
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        }

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        try {
            //发送用户登录成功信息
            Map<String,Object> msg = new HashMap<>();
            msg.put("id",user.getId());
            msg.put("date",System.currentTimeMillis());

            this.rocketMQTemplate.convertAndSend("tanhua-sso-login",msg);
        } catch (MessagingException e) {
            log.error("消息发送失败!",e);
        }

        return token + "|" + isNew;
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    @Override
    public User queryUserByToken(String token) {

        try {
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println(body); //{mobile=1333333333, id=2, exp=1605513392}

            User user = new User();
            user.setId(Long.valueOf(body.get("id").toString()));

            //需要返回user中的mobile,需要查询数据库获取到mobile;
            //如果每次都去查询数据库,必然会导致性能问题,所以需要将mobile进行缓存
            //数据缓存需要设置过期时间,过期时间要与token一致
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            if(this.redisTemplate.hasKey(redisKey)){
                String mobile = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            }else {
                //查询数据库
                User u = this.userMapper.selectById(user.getId());
                user.setMobile(u.getMobile());

                //将手机号存入Redis中
                //在jwt中的过期时间是: 秒
                long timeout = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey,u.getMobile(),timeout, TimeUnit.MILLISECONDS);
            }
            return user;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期!");
        } catch (Exception e) {
            log.error("token不合法, token = " + token, e);
        }

        return null;
    }

    /**
     * 修改手机号
     *
     * @param userId
     * @param newPhone
     * @return
     */
    @Override
    public Boolean updatePhone(Long userId, String newPhone) {

        //查询该手机号是否已经注册了
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", newPhone);
        User user = this.userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(user)){
            //手机号已经被注册
            return false;
        }

        user = new User();
        user.setId(userId);
        user.setMobile(newPhone);

        return this.userMapper.updateById(user) > 0;
    }
}
